package cc.booku.owlbox.InitPage;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.BottomBar.*;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.MainoldActivity;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.Decrypt;
import cc.booku.owlbox.Statistics.DataReport;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class InitPage extends Activity {
    private String ProfilePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator;
    private String ClassifyPath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "UserData/";

    private TextView var_JumpOver_Number, var_ArtDesign_Data, textView;
    private static final int MSG_REFRESH_PROGRESS = 1001;
    private static final int TIME_REFRESH = 8000;
    private TextRoundProgress trp135; // 起始角度设置为135

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        CrashHandler crashHandler = CrashHandler.getInstance();
//		crashHandler.init(getApplicationContext());

        setContentView(R.layout.initpage);
        textView = (TextView) findViewById(R.id.textView);
        //跳过
        var_JumpOver_Number = (TextView) findViewById(R.id.JumpOver_Number);
        //美工数据
        var_ArtDesign_Data = (TextView) findViewById(R.id.ArtDesign_Data);
        trp135 = (TextRoundProgress) findViewById(R.id.trp_135);
        //开始计时函数
        fun_StartCounting();
        //点击跳过函数
        //fun_JumpOver();
        GetSaying();
        //创建视频分类文件
        //Classify();

        //获取美工数据-移至handler
        //fun_ArtDesign();
        //点击美工数据查看更多
        //fun_MoreGraphicData();

        //读取文件数据查看是否需要重建

//		if (FileoOperations.fileIsExists(ProfilePath+"Profile.txt")) {
//			//存在就观察是否需要更新
//			ProfileUpdate();
//		}else {
//			//直接新建
//			FileoOperations.writeData(ProfilePath, "Profile", FileoOperations.readAssetsTxt(this, "TxtData/Profile"));
//		}


        //加入用户统计

        Log.d("initphone", "initphone----" + DataReport.initPhone(this));

        //请求一下数据库，将内容写入数据库
        //httpReport("http://192.168.1.102:2020/statistics/owlreport.php?"+DataReport.initPhone(this));
        String ProfileStr = FileoOperations.readAssetsTxt(InitPage.this, "TxtData/OwlReport");
        try {

            //读取配置文件信息
            JSONObject obj = JSONObject.parseObject(ProfileStr);
            String result = obj.getString("数据上报地址");

            String ciphertext = obj.getString("地址密文");
            String res = Decrypt.RsaDecrypt(InitPage.this, ciphertext);
            //HttpResponse(res+result,user_num);
            httpReport(res + result + DataReport.initPhone(this));
        } catch (Exception e) {

            Log.i("response===========>", "");
//异常处理
        }

    }

    private void GetSaying() {


        String BillBoard_B = FileoOperations.readAssetsTxt(InitPage.this, "TxtData/BillBoard");
        JSONObject objsd = JSONObject.parseObject(BillBoard_B);
        String result = objsd.getString("起始页小提醒");

        Message msg = new Message();
        msg.what = 2;
        Bundle bundle = new Bundle();
        bundle.putString("InitSaying", result);  //往Bundle中存放数据
        msg.setData(bundle);
        handler.sendMessage(msg);
        //InitSaying = result;
    }


    private void Classify() {


//如果存在
        if (FileoOperations.fileIsExists(ClassifyPath + "Classify.txt")) {

            //哪有那么多吊事，直接创建不就完了，又不是配置文件
            FileoOperations.deleteFile(InitPage.this, ClassifyPath + "Classify.txt");

            FileoOperations.writeData(ClassifyPath, "Classify", FileoOperations.readAssetsTxt(this, "TxtData/Classify"));
        } else {
            FileoOperations.writeData(ClassifyPath, "Classify", FileoOperations.readAssetsTxt(this, "TxtData/Classify"));
        }


//
//
//
//
//    	//比较两个文件版本
//
//		String Classify_A = FileoOperations.readAssetsTxt(this, "TxtData/Classify");
//		String Classify_SD = FileoOperations.readFromSDFile(this, ClassifyPath);
//		//读取配置文件信息
//		try {
//			JSONObject objsd = JSONObject.parseObject(Classify_SD);
//			String result_sd = objsd.getString("version");
//			JSONObject obja = JSONObject.parseObject(Classify_A);
//			String result_a = obja.getString("version");
//
//			//不包含文件就新建
//			if (!FileoOperations.fileIsExists(ClassifyPath+"Classify.txt")) {
//
//				FileoOperations.writeData(ClassifyPath, "Classify", FileoOperations.readAssetsTxt(this, "TxtData/Classify"));
//
//
//			}else{
//				//包含就判断版本
//				if (Integer.parseInt(result_sd) < Integer.parseInt(result_a)) {
//					//提示配置文件有更新
//					//是否重建
//					//直接重建
//
//					FileoOperations.deleteFile(InitPage.this, ClassifyPath+"Classify.txt");
//					FileoOperations.writeData(ClassifyPath, "Classify", FileoOperations.readAssetsTxt(this, "TxtData/Classify"));
//				}
//			}
//
//
//
//
//		} catch (Exception e) {
//
//			//没有读到版本号
//			//Toast.makeText(InitPage.this, "配置文件已经更新", Toast.LENGTH_SHORT).show();
//			//不包含---重建配置文件
//			if (!FileoOperations.fileIsExists(ClassifyPath+"Classify.txt")) {
//
//				FileoOperations.writeData(ClassifyPath, "Classify", FileoOperations.readAssetsTxt(this, "TxtData/Classify"));
//
//
//			}else{
//				Log.i("Classify===========>","Classify创建失败");
//			}
////异常处理
//		}


    }


//vod_imei=00000000-0f1f-0649-0000-00005e0676eb&vod_device=vivo&vod_model=V1938T&vod_language=zh&vod_version=7.1.2&vod_ip=10.0.2.15&vod_username=admin&vod_password=123456

    private void httpReport(String url) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.i("response===========>", res);

                //Mtoast60(res);


            }
        });

    }


    //有这一个就可以了
    private void ProfileUpdate() {


        String Profile_A = FileoOperations.readAssetsTxt(this, "TxtData/Profile");
        String Profile_SD = FileoOperations.readFromSDFile(this, ProfilePath + "Profile.txt");
        //读取配置文件信息
        try {
            JSONObject objsd = JSONObject.parseObject(Profile_SD);
            String result_sd = objsd.getString("配置文件版本");
            JSONObject obja = JSONObject.parseObject(Profile_A);
            String result_a = obja.getString("配置文件版本");


            if (Integer.parseInt(result_sd) < Integer.parseInt(result_a)) {
                //提示配置文件有更新
                //是否重建
                //直接重建

                FileoOperations.deleteFile(InitPage.this, ProfilePath + "Profile.txt");
                FileoOperations.writeData(ProfilePath, "Profile", FileoOperations.readAssetsTxt(this, "TxtData/Profile"));
            }


        } catch (Exception e) {

            Toast.makeText(InitPage.this, "配置文件已经更新", Toast.LENGTH_SHORT).show();
            //不包含---重建配置文件
            FileoOperations.deleteFile(InitPage.this, ProfilePath + "Profile.txt");
            FileoOperations.writeData(ProfilePath, "Profile", FileoOperations.readAssetsTxt(this, "TxtData/Profile"));
//异常处理
        }

    }


    private int timer_flag = 0;

    private void fun_StartCounting() {
        //绘制美工用的参数
        Message msg = new Message();
        msg.what = 6;
        handler.sendMessage(msg);

        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                Message msg = new Message();
                msg.what = 1;
                msg.obj = timer_flag;
                handler.sendMessage(msg);
                timer_flag++;
                if (timer_flag > 4) {
                    timer_flag = 5;
                    timer.cancel();//取消计时
                    finish();//关闭销毁该页面
                    Intent intent = new Intent(InitPage.this, FragmentManagerActivity.class);
                    startActivity(intent);
                    //fun_JumpOver();

                }

            }
        }, 4, 1000);
    }


    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                //var_JumpOver_Number.setText(msg.obj+"校验本地文件");
                trp135.setProgress((Integer) msg.obj);
            }
            if (msg.what == 2) {
                String str1 = msg.getData().getString("InitSaying");//接受msg传递过来的参数
                InitSaying = str1;

                textView.setText(sentence_init());

            }
            if (msg.what == 6) {
                fun_ArtDesign();
            }
        }
    };


    private String InitSaying = "";

    private String sentence_init() {

        String[] InitSayingArray = InitSaying.split("[|]");
        //Log.d("1111", "onResponse:json " +InitSayingArray[2]);


        int a = (int) (1 + Math.random() * (10 - 1 + 1));
        String sentence = "";
        if (a == 1) {
            sentence = InitSayingArray[0];
        }
        if (a == 2) {
            sentence = InitSayingArray[1];
        }
        if (a == 3) {
            sentence = InitSayingArray[2];
        }
        if (a == 4) {
            sentence = InitSayingArray[3];
        }
        if (a == 5) {
            sentence = InitSayingArray[4];
        }
        if (a == 6) {
            sentence = InitSayingArray[5];
        }
        if (a == 7) {
            sentence = InitSayingArray[6];
        }
        if (a == 8) {
            sentence = InitSayingArray[7];
        }
        if (a == 9) {
            sentence = InitSayingArray[8];
        }
        if (a == 10) {
            sentence = InitSayingArray[9];
        }

        return (sentence);

    }


    private void fun_JumpOver() {

        var_JumpOver_Number.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //finish();  //关闭销毁该页面
                Intent intent = new Intent(InitPage.this, MainoldActivity.class);
                startActivity(intent);
            }

        });
    }


    private void fun_ArtDesign() {

        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        int screenHeight = (int) (height / density);// 屏幕高度(dp)


        var_ArtDesign_Data.setText(
                "px：" + width + " x " + height + "\n" +
                        "dp：" + screenWidth + " x " + screenHeight + "\n" +
                        "网络：" + SystemUtil.getNetworkType(this)
        );

        /**
         * "屏幕尺寸参数：\n" +
         "宽度（px）：" + width+"\n" +
         "高度（px）：" + height+"\n" +
         "密度（0.75 / 1.0 / 1.5）：" + density+"\n" +
         "密度dpi（120 / 160 / 240）：" + densityDpi+"\n" +
         "宽度（dp）：" + screenWidth+"\n" +
         "高度（dp）：" + screenHeight+"\n\n" +
         "系统参数：\n" +//系统
         "手机厂商：" + SystemUtil.getDeviceBrand()+"\n" +
         "手机型号：" + SystemUtil.getSystemModel()+"\n" +
         "系统语言：" + SystemUtil.getSystemLanguage()+"\n" +
         "Android系统版本号：" + SystemUtil.getSystemVersion()+"\n" +
         "是否root："+SystemUtil.isSystemRoot()+"\n" +
         "网络类型："+SystemUtil.getNetworkType(this)+"\n" +
         "OS名称："+System.getProperty("os.name")+"\n" +
         "OS版本号："+System.getProperty("os.version")+"\n" +
         "OS架构：" + System.getProperty("os.arch")+"\n" +
         "编译时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date(Build.TIME))+"\n\n" +
         "硬件参数：\n" +//硬件
         "主板：" + Build.BOARD+"\n"+
         "cpu型号："+SystemUtil.getCpuInfo()+"\n" +//返回cpu参数
         "可用RAM大小："+SystemUtil.getAvailMemory(this)+"\n" +//返回已使用的内存
         "总内存："+SystemUtil.getTotalMemory(this)+"\n" +//返回总内存
         "MAC地址："+SystemUtil.getLocalMacAddress(this)+"\n" +
         "显示屏参数：" + Build.DISPLAY+"\n" +
         "屏幕尺寸：" + SystemUtil.getWeithAndHeight(this)
         */

        /*
            Log.d("h_bl", "屏幕宽度（像素）：" + width);
            Log.d("h_bl", "屏幕高度（像素）：" + height);
            Log.d("h_bl", "屏幕密度（0.75 / 1.0 / 1.5）：" + density);
            Log.d("h_bl", "屏幕密度dpi（120 / 160 / 240）：" + densityDpi);
            Log.d("h_bl", "屏幕宽度（dp）：" + screenWidth);
            Log.d("h_bl", "屏幕高度（dp）：" + screenHeight);


            String TAG = "系统参数：";
        Log.e(TAG, "手机厂商：" + SystemUtil.getDeviceBrand());
        Log.e(TAG, "手机型号：" + SystemUtil.getSystemModel());
        Log.e(TAG, "手机当前系统语言：" + SystemUtil.getSystemLanguage());
        Log.e(TAG, "Android系统版本号：" + SystemUtil.getSystemVersion());
        Log.e(TAG, "手机IMEI：" + getUniquePsuedoID());
*/

    }

    private void fun_MoreGraphicData() {

        var_ArtDesign_Data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(InitPage.this, "保留暂不处理", Toast.LENGTH_LONG).show();
                //finish();  //关闭销毁该页面

            }

        });


    }

}

